/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.rcs.folders;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author pablo
 */
public abstract class FactoryFolder extends AbstractFolder {

  private ItemsFactory[] factories;
  private String name;

  public FactoryFolder(String name, ItemsFactory[] factories) {
    this.name = name;
    this.factories = factories;
  }

  protected ItemsFactory[] getFactories() {
    return factories;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public List<? extends VirtualItem> getChildren() {
    List<VirtualItem> result = new ArrayList<VirtualItem>();

    for (ItemsFactory factory : factories)
      if (factory.isEnabled()) {
        VirtualItem[] factoryItems = getChildren(factory);

        if (null != factoryItems) {
          for (VirtualItem item : factoryItems) {
            if (item instanceof VirtualFolder)
              tryAddItems(factory.getName(), result, ((VirtualFolder) item).getChildren());
            else
              tryAddItem(factory.getName(), result, item);
          }
        }
      }

    return result;
  }

  protected void tryAddItem(String factoryName, List<VirtualItem> result, VirtualItem item) {
      if (hasItem(item, result))
        result.add(createWrapperItem(item, factoryName));
      else
        result.add(item);
  }
  
  protected void tryAddItems(String factoryName, List<VirtualItem> result, List<? extends VirtualItem> items) {
    for (VirtualItem item : items)
      tryAddItem(factoryName, result, item) ;
  }

  protected VirtualItem createWrapperItem(VirtualItem item, String factoryName) {
    String name = String.format("(on %s) %s", factoryName, item.getDisplayName());

    if (item instanceof VirtualFolder)
      return new WrapperFolder((VirtualFolder) item, name);
    else
      return new WrapperItem(item, name);
  }

  protected abstract VirtualItem[] getChildren(ItemsFactory factory);
}
